package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

@WebFilter("/demo")
public class FilterDemo01 implements Filter {
    //定义最大请求数量
    private static final int MAX_COUNT = 5;
    //定义计数器  get()方法获取当前线程个数
    private AtomicInteger filterCount = new AtomicInteger(0);

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //如果超过最大请求数就跳转到排队页面
        if (filterCount.get()>MAX_COUNT){
            //使用重定向，跳转到index.jsp页面
            response.sendRedirect("index.jsp");
            return;
        } else {
            //如果请求个数没超过  请求个数加1
            filterCount.incrementAndGet();
            //放行
            chain.doFilter(request, response);
            //请求个数减一
            filterCount.decrementAndGet();
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}